package com.xiaohai.big_event_system.controller;


import com.xiaohai.big_event_system.annotation.LogExecutionTime;
import com.xiaohai.big_event_system.common.R;
import com.xiaohai.big_event_system.projo.User;
import com.xiaohai.big_event_system.service.IUserService;
import com.xiaohai.big_event_system.utils.JwtUtil;
import com.xiaohai.big_event_system.utils.Md5Util;
import com.xiaohai.big_event_system.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户表
 *
 * @author author
 * @since 2025-01-15
 */
@RestController
@RequestMapping("/user")
@Validated
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 注册
     * 注册新用户
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public R<String> register(@NotNull @Pattern(regexp = "^\\{5,16}}$") String username, @NotNull @Pattern(regexp = "^\\{5,16}}$") String password) {
        log.info("userbane:{},pass:{}", username, password);
        User user = userService.findByUserName(username);
        if (user == null) {
            userService.register(username, password);
            return R.success(null, "注册成功");
        } else {
            return R.error(201, "用户名已被注册");
        }
    }


    /**
     * 登录
     * 根据账号和密码登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@NotNull @Pattern(regexp = "^.{5,16}$", message = "用户名长度必须在5到16个字符之间") String username, @NotNull @Pattern(regexp = "^.{5,16}$", message = "密码长度必须在5到16个字符之间") String password) {
        User user = userService.findByUserName(username);
        if (user == null) {
            return R.error(201, "用户名不存在");
        }
        if (Md5Util.checkPassword(password, user.getPassword())) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("username", user.getUsername());
            String token = JwtUtil.createToken(map);

            // 登录成功，将token存入redis
            redisTemplate.opsForValue().set("token_" + token, username, 1, TimeUnit.HOURS);
            return R.success(token, "登录成功");
        }
        return R.error(201, "密码错误，登录失败");
    }

    /**
     * 用户信息
     * 获取用户信息
     *
     * @return
     */
    @LogExecutionTime(description = "获取用户信息接口")
    @GetMapping
    public R<User> userInfo(/*@RequestHeader("Authorization") String token*/) {
//        Map<String, Object> map = JwtUtil.parseToken(token);
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return R.success(user, "获取信息成功");
    }

    /**
     * 更新用户信息
     * 更新接口
     *
     * @param user
     * @return
     */
    @PutMapping("/update")
    public R<String> update(@RequestBody @Valid User user) {
        boolean b = userService.updateById(user);
        return R.success(null, "更新信息成功");
    }

    /**
     * 更新头像
     * 头像
     *
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public R<String> updateAvatar(@NotNull @URL String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        user.setUserPic(avatarUrl);
        userService.updateById(user);
        return R.success(null, "更新头像成功");
    }


    /**
     * 修改密码
     * 修改密码
     *
     * @param params
     * @return
     */
    @PostMapping("/updatePw")
    public R<String> updatePad(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        String password = user.getPassword();
        log.info("params:{}", params);

        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String conPwd = params.get("con_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(conPwd)) {
            return R.error(201, "参数有误");
        }
        if (!newPwd.equals(conPwd)) {
            return R.error(201, "两次密码不一致");
        }
        if (Md5Util.getMD5String(conPwd).equals(password)) {
            return R.error(201, "新密码不能与旧密码相同");
        }
        user.setPassword(Md5Util.getMD5String(conPwd));
        userService.updateById(user);

        // 修改密码成功后，删除redis中的token
        redisTemplate.delete("token_" + token);
        return R.success(null, "修改密码成功");
    }
}
